var loadings = 0;
var timezoneOffset = (new Date()).getTimezoneOffset() / 60;
function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};


/**
 * jQuery JSON Plugin
 * version: 2.3 (2011-09-17)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
 * website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.
 *
 * It is also influenced heavily by MochiKit's serializeJSON, which is
 * copyrighted 2005 by Bob Ippolito.
 */
(function ($) {
    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
        meta = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        };

    /**
     * jQuery.toJSON
     * Converts the given argument into a JSON respresentation.
     *
     * @param o {Mixed} The json-serializble *thing* to be converted
     *
     * If an object has a toJSON prototype, that will be used to get the representation.
     * Non-integer/string keys are skipped in the object, as are keys that point to a
     * function.
     *
     */
    $.toJSON = typeof JSON === 'object' && JSON.stringify
        ? JSON.stringify
        : function (o) {

        if (o === null) {
            return 'null';
        }

        var type = typeof o;

        if (type === 'undefined') {
            return undefined;
        }
        if (type === 'number' || type === 'boolean') {
            return '' + o;
        }
        if (type === 'string') {
            return $.quoteString(o);
        }
        if (type === 'object') {
            if (typeof o.toJSON === 'function') {
                return $.toJSON(o.toJSON());
            }
            if (o.constructor === Date) {
                var month = o.getUTCMonth() + 1,
                    day = o.getUTCDate(),
                    year = o.getUTCFullYear(),
                    hours = o.getUTCHours(),
                    minutes = o.getUTCMinutes(),
                    seconds = o.getUTCSeconds(),
                    milli = o.getUTCMilliseconds();

                if (month < 10) {
                    month = '0' + month;
                }
                if (day < 10) {
                    day = '0' + day;
                }
                if (hours < 10) {
                    hours = '0' + hours;
                }
                if (minutes < 10) {
                    minutes = '0' + minutes;
                }
                if (seconds < 10) {
                    seconds = '0' + seconds;
                }
                if (milli < 100) {
                    milli = '0' + milli;
                }
                if (milli < 10) {
                    milli = '0' + milli;
                }
                return '"' + year + '-' + month + '-' + day + 'T' +
                    hours + ':' + minutes + ':' + seconds +
                    '.' + milli + 'Z"';
            }
            if (o.constructor === Array) {
                var ret = [];
                for (var i = 0; i < o.length; i++) {
                    ret.push($.toJSON(o[i]) || 'null');
                }
                return '[' + ret.join(',') + ']';
            }
            var name,
                val,
                pairs = [];
            for (var k in o) {
                type = typeof k;
                if (type === 'number') {
                    name = '"' + k + '"';
                } else if (type === 'string') {
                    name = $.quoteString(k);
                } else {
                    // Keys must be numerical or string. Skip others
                    continue;
                }
                type = typeof o[k];

                if (type === 'function' || type === 'undefined') {
                    // Invalid values like these return undefined
                    // from toJSON, however those object members
                    // shouldn't be included in the JSON string at all.
                    continue;
                }
                val = $.toJSON(o[k]);
                pairs.push(name + ':' + val);
            }
            return '{' + pairs.join(',') + '}';
        }
    };

    /**
     * jQuery.evalJSON
     * Evaluates a given piece of json source.
     *
     * @param src {String}
     */
    $.evalJSON = typeof JSON === 'object' && JSON.parse
        ? JSON.parse
        : function (src) {
        return eval('(' + src + ')');
    };

    /**
     * jQuery.secureEvalJSON
     * Evals JSON in a way that is *more* secure.
     *
     * @param src {String}
     */
    $.secureEvalJSON = typeof JSON === 'object' && JSON.parse
        ? JSON.parse
        : function (src) {

        var filtered =
            src
                .replace(/\\["\\\/bfnrtu]/g, '@')
                .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                .replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered)) {
            return eval('(' + src + ')');
        } else {
            throw new SyntaxError('Error parsing JSON, source is not valid.');
        }
    };

    /**
     * jQuery.quoteString
     * Returns a string-repr of a string, escaping quotes intelligently.
     * Mostly a support function for toJSON.
     * Examples:
     * >>> jQuery.quoteString('apple')
     * "apple"
     *
     * >>> jQuery.quoteString('"Where are we going?", she asked.')
     * "\"Where are we going?\", she asked."
     */
    $.quoteString = function (string) {
        if (string.match(escapeable)) {
            return '"' + string.replace(escapeable, function (a) {
                    var c = meta[a];
                    if (typeof c === 'string') {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                }) + '"';
        }
        return '"' + string + '"';
    };

})(jQuery);

(function ($, undefined) {
    var tag2attr = {
            a: 'href',
            img: 'src',
            form: 'action',
            base: 'href',
            script: 'src',
            iframe: 'src',
            link: 'href'
        },

        key = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "fragment"], // keys available to query

        aliases = {"anchor": "fragment"}, // aliases for backwards compatability

        parser = {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, //less intuitive, more accurate to the specs
            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
        },

        querystring_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g, // supports both ampersand and semicolon-delimted query string key/value pairs

        fragment_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g; // supports both ampersand and semicolon-delimted fragment key/value pairs

    function parseUri(url, strictMode) {
        var str = decodeURI(url),
            res = parser[strictMode || false ? "strict" : "loose"].exec(str),
            uri = {attr: {}, param: {}, seg: {}},
            i = 14;

        while (i--) {
            uri.attr[key[i]] = res[i] || "";
        }

        // build query and fragment parameters

        uri.param['query'] = {};
        uri.param['fragment'] = {};

        uri.attr['query'].replace(querystring_parser, function ($0, $1, $2) {
            if ($1) {
                uri.param['query'][$1] = $2;
            }
        });

        uri.attr['fragment'].replace(fragment_parser, function ($0, $1, $2) {
            if ($1) {
                uri.param['fragment'][$1] = $2;
            }
        });

        // split path and fragement into segments

        uri.seg['path'] = uri.attr.path.replace(/^\/+|\/+$/g, '').split('/');

        uri.seg['fragment'] = uri.attr.fragment.replace(/^\/+|\/+$/g, '').split('/');

        // compile a 'base' domain attribute

        uri.attr['base'] = uri.attr.host ? uri.attr.protocol + "://" + uri.attr.host + (uri.attr.port ? ":" + uri.attr.port : '') : '';

        return uri;
    };

    function getAttrName(elm) {
        var tn = elm.tagName;
        if (tn !== undefined) return tag2attr[tn.toLowerCase()];
        return tn;
    }

    $.fn.url = function (strictMode) {
        var url = '';

        if (this.length) {
            url = $(this).attr(getAttrName(this[0])) || '';
        }

        return $.url(url, strictMode);
    };

    $.url = function (url, strictMode) {
        if (arguments.length === 1 && url === true) {
            strictMode = true;
            url = undefined;
        }

        strictMode = strictMode || false;
        url = url || window.location.toString();

        return {

            data: parseUri(url, strictMode),

            // get various attributes from the URI
            attr: function (attr) {
                attr = aliases[attr] || attr;
                return attr !== undefined ? this.data.attr[attr] : this.data.attr;
            },

            // return query string parameters
            param: function (param) {
                return param !== undefined ? this.data.param.query[param] : this.data.param.query;
            },

            // return fragment parameters
            fparam: function (param) {
                return param !== undefined ? this.data.param.fragment[param] : this.data.param.fragment;
            },

            // return path segments
            segment: function (seg) {
                if (seg === undefined) {
                    return this.data.seg.path;
                }
                else {
                    seg = seg < 0 ? this.data.seg.path.length + seg : seg - 1; // negative segments count from the end
                    return this.data.seg.path[seg];
                }
            },

            // return fragment segments
            fsegment: function (seg) {
                if (seg === undefined) {
                    return this.data.seg.fragment;
                }
                else {
                    seg = seg < 0 ? this.data.seg.fragment.length + seg : seg - 1; // negative segments count from the end
                    return this.data.seg.fragment[seg];
                }
            }

        };

    };

})(jQuery);

/**
 *GUID
 * @type {{newGuid: guid.newGuid, empty: guid.empty}}
 */
var guid = {
    newGuid: function () {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    empty: function () {
        return "00000000-0000-0000-0000-000000000000";
    }
};
/**
 * 系统前端上下文
 * @type {{token: *, userId: *, email: *, name: *, loginName: *}}
 */
var context = {
    token: $.cookie(app.name + '_token'),
    userId: $.cookie(app.name + '_userId'),
    email: $.cookie(app.name + '_email'),
    name: $.cookie(app.name + '_name'),
    loginName: $.cookie(app.name + '_loginName')
}
/**
 * 服务访问
 */
jQuery.extend({

    request: function (url, data, success, error, loading, async) {
        if (!$.isFunction(error)) {
            async = loading;
            loading = error;
        }
        if (loading == undefined) {
            loading = true;
        }
        if (loading) {
            if (loadings == 0) {
                // $("#loading").show();
                $(".loading-masks").removeClass('loading-inactive');
            }
            loadings++;
        }
        if (async == undefined) {
            async = true;
        }
        var mydata = $.toJSON(data);
        console.log(mydata);
        return jQuery.ajax({

            url: url + "?token=" + context.token,
            type: 'post',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            async: async,
            data: mydata,
            success: function (result) {
                if (success) {
                    success(result);
                }
            },
            error: function (result) {
                if (result.status == 600) {
                    alert(result.responseText)
                } else if (result.status == 604) {
                    alert(result.responseText)
                    window.parent.location.href = '/login.html?license=' + new Date().getTime();
                } else if (result.status == 602) {
                    alert(result.responseText)
                } else if (result.status == 605) {
                    alert(result.responseText)
                }
                if (error) {
                    error(result);
                }
            }
        }).always(function () {
            if (loading) {
                loadings--;
                if (loadings == 0) {
                    // $("#loading").hide();
                    $('.loading-masks').addClass('loading-inactive');
                }
            }
        });
    },
    upload: function (data, success, error, loading) {
        if (!$.isFunction(error)) {
            loading = error;
        }
        if (loading == undefined) {
            loading = true;
        }
        if (loading) {
            if (loadings == 0) {
                $(".loading-masks").removeClass('loading-inactive');
            }
            loadings++;
        }
        return jQuery.ajax({
            url: '/com/upload/do?token=' + context.token,
            type: 'POST',
            enctype: "multipart/form-data",
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            data: data,
            success: function (result) {
                if (success) {
                    success(result);
                }
            },
            error: function (result) {
                if (result.status == 600) {
                    alert(result.responseText)
                } else if (result.status == 604) {
                    alert(result.responseText)
                    window.parent.location.href = '/login.html?license=' + new Date().getTime();
                } else if (result.status == 602) {
                    alert(result.responseText)
                } else if (result.status == 605) {
                    alert(result.responseText)
                }
                if (error) {
                    error(result);
                }
            }
        }).always(function () {
            if (loading) {
                loadings--;
                if (loadings == 0) {
                    $('.loading-masks').addClass('loading-inactive');
                }
            }
        });
    },
    setobject: function (data, scope) {
        $.each(data, function (id, value) {
            var control;
            if (scope) {
                control = $("#" + scope + " #" + id);
            } else {
                control = $("#" + id);
            }
            if (control.is("input[type='text']") || control.is("label") || control.is("input[type='password']") || control.is("input[type='hidden']")) {
                if (control.attr('data-date-format')) {
                    value = moment(value).formatUTC(control.attr('data-date-format'));
                }
                if (control.is("label")) {
                    if (value != null) {
                        control.text(value);
                    }
                    else {
                        control.text('');
                    }
                }
                else
                    control.val(value);
            }
            else if (control.is('textarea')) {
                control.val(value);
            }
            else if (control.is("input[type='radio']")) {
                $("#input[name='" + id + "']").each(function (i, e) {
                    if (e.val() == value) {
                        e.checked == true;
                        return false;
                    }
                })
            }
            else if (control.is("input[type='number']")) {
                control.val(value);
            }
            else if (control.is('select')) {
                control.val(value);
                //control.find("option[value=" + value + "]").attr("selected", true);
            }
        })
    }
});


$.fn.setobject = function (data) {
    var $this = $(this);
    for (i in data) {
        var control = $this.find("[name=" + i + "]");
        if (control.length > 0) {
            var value = data[i];
            if (value) {
                if (control.attr('data-date-format'))
                    value = moment(value).formatUTC(control.attr('data-date-format'));
                if (control.is("input") || control.is("textarea")) {
                    control.val(value);
                }
                else if (control.is('label')) {
                    control.html(value);
                } else if (control.is('select')) {
                    control.val(value);
                    control.trigger('change');
                }
            }
        }
    }

}

$.format = function (source, params) {
    if (arguments.length == 1)
        return function () {
            var args = $.makeArray(arguments);
            args.unshift(source);
            return $.format.apply(this, args);
        };
    if (arguments.length > 2 && params.constructor != Array) {
        params = $.makeArray(arguments).slice(1);
    }
    if (params.constructor != Array) {
        params = [params];
    }
    $.each(params, function (i, n) {
        source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
    });
    return source;
};


var currentColor;

function getCurrentColor() {
    var colorList = {
        'azure': '#2dc3e8', 'black': '#474544', 'blue': '#5db2ff',
        'darkblue': '#0072c6', 'darkred': '#ac193d', 'deepblue': '#001940',
        'gray': '#585858', 'green': '#53a93f', 'orange': '#ff8f32',
        'pink': '#cc324b', 'purple': '#8c0095', 'teal': '#03b3b2'
    };
    if ($.cookie('current-skin'))
        return colorList[$.cookie('current-skin').replace('/assets/css/skins/', '').replace('.min.css', '')];
    else {
        $.cookie('current-skin', "/assets/css/skins/darkblue.min.css");
        return colorList[$.cookie('current-skin').replace('/assets/css/skins/', '').replace('.min.css', '')];
    }
    return colorList.darkblue;
}

(function () {
    currentColor = getCurrentColor();
})();


QueryString = {
    data: {},
    Initial: function () {
        var aPairs, aTmp;
        var queryString = new String(window.location.search);
        queryString = queryString.substr(1, queryString.length); //remove   "?"
        aPairs = queryString.split("&");
        for (var i = 0; i < aPairs.length; i++) {
            aTmp = aPairs[i].split("=");
            this.data[aTmp[0]] = aTmp[1];
        }
    },
    GetValue: function (key) {
        return this.data[key] ? this.data[key] : "";
    }
};

$.Request = {
    QueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;

    }
}

String.prototype.QueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var sp = this.split('?');
    if (sp.length > 1) {
        var r = this.split('?')[1].match(reg);
        if (r != null) return unescape(r[2]);
    }
    return null;
}
var util = {
    browserVersion: function () {
        var Sys = {};
        var ua = navigator.userAgent.toLowerCase();
        var s;
        (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1] :
            (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
                (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                    (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                            (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

        return Sys;
    },

    isIE: function () {
        var obj = this.browserVersion();
        if (obj.ie)
            return true;
        else
            return false;
    },

    openUrl: function (url, type, name, width, height, left, top) {
        var availWidth = screen.availWidth - 20;
        var availHeight = screen.availHeight - 70;
        //var availWidth = screen.availWidth ;
        //var availHeight = screen.availHeight ;
        var myWidth = width ? width : availWidth;
        var myHeight = height ? height : availHeight;
        var myLeft = left ? left : (availWidth - myWidth) / 2;
        var myTop = top ? left : (availHeight - myHeight) / 2;
        if (!name)
            name = "";
        if (this.isIE() && type == 'modal') {
            var returnValue = window.showModalDialog(url, window, "edge:raised;scroll:1;status:0;help:0;resizable:1;dialogWidth:" + myWidth + "px;dialogHeight:" + myHeight + "px;dialogTop:" + myTop + "px;dialogLeft:" + myLeft + "px", true);
            if (returnValue == undefined) {
                returnValue = window.returnValue;
            }
            return returnValue;
        }
        else {
            var opened = window.open(url, name, 'height=' + myHeight + ',width=' + myWidth + ',status=1,toolbar=no,menubar=no,location=no,scrollbars=yes,modal=yes,dependent=yes,dialog=yes,minimizable=no,top=' + myTop + ',left=' + myLeft + ',resizable=yes', true);
            opened.focus();
            return opened;
        }

    }

}
